package com.sluggard.ai.tools;

import com.sluggard.ai.controller.KnowledgeController;
import com.sluggard.ai.model.entity.KnowledgeEntity;
import com.sluggard.ai.model.req.KnowledgeReq;
import com.sluggard.ai.service.IKnowledgeService;
import com.sluggard.common.model.res.Result;
import com.sluggard.mp.model.req.IdReq;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author lizheng
 * @created 2025/4/24 14:35
 */
@Slf4j
@Component
public class SystemTools {

    @Resource
    KnowledgeController knowledgeController;

    @Resource
    private IKnowledgeService knowledgeService;

    @Tool(description = "create knowledge")
    String createKnowledge(@ToolParam(description = "知识库名称") String name, @ToolParam(description = "知识库描述") String description) {
        KnowledgeEntity knowledge = knowledgeService.findKnowledgeByName(name);
        if (Objects.nonNull(knowledge)) {
            return "知识库已存在";
        }
        log.info("创建知识库 {}", name);
        KnowledgeReq knowledgeReq = new KnowledgeReq();
        knowledgeReq.setName(name);
        knowledgeReq.setDescription(description);
        knowledgeController.save(knowledgeReq);
        return "知识库创建成功";
    }

    @Tool(description = "delete knowledge")
    String deleteKnowledge(@ToolParam(description = "知识库名称") String name) {
        KnowledgeEntity knowledge = knowledgeService.findKnowledgeByName(name);
        if (Objects.nonNull(knowledge)) {
            knowledgeController.deleteById(new IdReq(knowledge.getId()));
        }
        return "知识库已删除";
    }

    @Tool(description = "update knowledge")
    String updateKnowledge(@ToolParam(description = "原知识库名称") String oldName,
                            @ToolParam(description = "新知识库名称") String newName,
                            @ToolParam(description = "new知识库描述") String description) {
        KnowledgeEntity knowledge = knowledgeService.findKnowledgeByName(oldName);
        if (Objects.nonNull(knowledge)) {
            knowledge.setName(newName);
            knowledge.setDescription(description);
            knowledgeService.updateById(knowledge);
        }
        return "知识库已更新";
    }

    @Tool(description = "knowledge list")
    List<Map<String, String>> knowledgeList() {
        return knowledgeService.list()
                .parallelStream()
                .map(item -> Map.of("name", item.getName(), "description", item.getDescription())).toList();
    }

}
